package org.nyt.medicalstore.controller;

import org.nyt.medicalstore.model.PurchaseRecord;
import org.nyt.medicalstore.service.PurchaseRecordService;
import org.nyt.medicalstore.dto.PurchaseRecordDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/purchaserecords")
public class PurchaseRecordController {
    @Autowired
    private PurchaseRecordService purchaseRecordService;

    private PurchaseRecordDTO toDTO(PurchaseRecord record) {
        if (record == null) return null;
        PurchaseRecordDTO dto = new PurchaseRecordDTO();
        dto.setId(record.getId());
        dto.setDrugId(record.getDrug() != null ? record.getDrug().getId() : null);
        dto.setSupplierId(record.getSupplier() != null ? record.getSupplier().getId() : null);
        dto.setQuantity(record.getQuantity());
        dto.setPurchaseDate(record.getPurchaseDate());
        return dto;
    }

    @PostMapping
    public PurchaseRecordDTO addPurchaseRecord(@RequestBody PurchaseRecord purchaseRecord) {
        return toDTO(purchaseRecordService.savePurchaseRecord(purchaseRecord));
    }

    @GetMapping("/{id}")
    public PurchaseRecordDTO getPurchaseRecord(@PathVariable Long id) {
        return toDTO(purchaseRecordService.getPurchaseRecordById(id));
    }

    @GetMapping
    public List<PurchaseRecordDTO> getAllPurchaseRecords() {
        return purchaseRecordService.getAllPurchaseRecords().stream().map(this::toDTO).collect(Collectors.toList());
    }

    @DeleteMapping("/{id}")
    public void deletePurchaseRecord(@PathVariable Long id) {
        purchaseRecordService.deletePurchaseRecord(id);
    }
} 